// checksum 0xa193 version 0x30001
///////////////////////////////////////////////
//Author: Juhapekka Piiroinen
//License: GPLv3
//Webpage: http://code.google.com/p/cutechat
///////////////////////////////////////////////

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtCore/QCoreApplication>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
//#ifdef __DEBUG__
    QXmppLogger::getLogger()->setLoggingType(QXmppLogger::StdoutLogging);
//#endif
    m_client = new QXmppClient(this);
    connect(m_client,SIGNAL(messageReceived(QXmppMessage)),this,SLOT(messageReceived(QXmppMessage)));
    connect(m_client,SIGNAL(presenceReceived(QXmppPresence)),this,SLOT(presenceReceived(QXmppPresence)));
    connect(&m_client->rosterManager(),SIGNAL(rosterReceived()),this,SLOT(rosterReceived()));
    connect(&m_client->vCardManager(), SIGNAL(vCardReceived(const QXmppVCardIq&)),this,SLOT(vCardReceived(const QXmppVCardIq&)));
}

MainWindow::~MainWindow()
{
    if (m_client) {
        if (m_client->isConnected()) {
            m_client->disconnectFromServer();
        }
        m_client->deleteLater();
    }


    delete ui;
}

void MainWindow::setOrientation(ScreenOrientation orientation)
{
#if defined(Q_OS_SYMBIAN)
    // If the version of Qt on the device is < 4.7.2, that attribute won't work
    if (orientation != ScreenOrientationAuto) {
        const QStringList v = QString::fromAscii(qVersion()).split(QLatin1Char('.'));
        if (v.count() == 3 && (v.at(0).toInt() << 16 | v.at(1).toInt() << 8 | v.at(2).toInt()) < 0x040702) {
            qWarning("Screen orientation locking only supported with Qt 4.7.2 and above");
            return;
        }
    }
#endif // Q_OS_SYMBIAN

    Qt::WidgetAttribute attribute;
    switch (orientation) {
#if QT_VERSION < 0x040702
    // Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes
    case ScreenOrientationLockPortrait:
        attribute = static_cast<Qt::WidgetAttribute>(128);
        break;
    case ScreenOrientationLockLandscape:
        attribute = static_cast<Qt::WidgetAttribute>(129);
        break;
    default:
    case ScreenOrientationAuto:
        attribute = static_cast<Qt::WidgetAttribute>(130);
        break;
#else // QT_VERSION < 0x040702
    case ScreenOrientationLockPortrait:
        attribute = Qt::WA_LockPortraitOrientation;
        break;
    case ScreenOrientationLockLandscape:
        attribute = Qt::WA_LockLandscapeOrientation;
        break;
    default:
    case ScreenOrientationAuto:
        attribute = Qt::WA_AutoOrientation;
        break;
#endif // QT_VERSION < 0x040702
    };
    setAttribute(attribute, true);
}

void MainWindow::showExpanded()
{
#ifdef Q_OS_SYMBIAN
    showFullScreen();
#elif defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
    showMaximized();
#else
    show();
#endif
}

void MainWindow::rosterReceived() {
    QStringList list = m_client->rosterManager().getRosterBareJids();
    for(int i = 0; i < list.size(); ++i) {
        // request vCard of all the bareJids in roster
        //QString filename = QString("%0.vcard").arg(list.at(i));
        //if (QFile::exists(QString("%0.png").arg(bareJid))==false) {
            m_client->vCardManager().requestVCard(list.at(i));
       // }

    }
}

void MainWindow::vCardReceived(const QXmppVCardIq& vCard) {
    QString bareJid = vCard.from();
    QString fullName =vCard.fullName();
    QString nickName = vCard.nickName();

    QByteArray photo = vCard.photo();

    QBuffer buffer;
    buffer.setData(photo);
    buffer.open(QIODevice::ReadOnly);
    QImageReader imageReader(&buffer);
    QImage image = imageReader.read();
    ///image.save(QString("%0.png").arg(bareJid),"png");
    updateRoster(bareJid,fullName,nickName,image);
}

void MainWindow::updateRoster(QString bareJid, QString fullName, QString nickName, QImage avatar) {

  foreach (ContactPage* page, m_contacts) {
      if (page->getBareJid()==bareJid) {
          page->updateRoster(bareJid,fullName,nickName,avatar);
          return;
      }
  }
  ContactPage* newPage = new ContactPage(bareJid);
  connect(newPage,SIGNAL(sendMessage(QString)),this,SLOT(sendMessage(QString)));

  ui->toolBox->addItem(newPage,QIcon(QPixmap::fromImage(avatar)),QString("%0 - %1").arg(fullName).arg(bareJid));
  if (ui->toolBox->itemText(0)=="Loading Contacts..") {
      ui->toolBox->removeItem(0);
  }
  m_contacts.append(newPage);
}

void MainWindow::messageReceived(QXmppMessage msg) {
    //qDebug() << msg.from();
    //ui->plainTextEdit->appendPlainText(QString("%3 [%0] %1: %2").arg(msg.stamp().toString()).arg(msg.from()).arg(msg.body()).arg(msg.id()));
    QString bareJid = msg.from();
    bareJid = bareJid.split("/").at(0);

    foreach (ContactPage* page, m_contacts) {
        if (page->getBareJid()==bareJid) {
            page->receiveMessage(msg.body());
            return;
        }
    }
    m_client->vCardManager().requestVCard(bareJid);
}

void MainWindow::presenceReceived(QXmppPresence pre) {
    //ui->plainTextEdit->appendPlainText(QString("%0: %1 (%2)").arg(pre.from()).arg(pre.status().type()).arg(pre.status().getStatusText()));
    QByteArray shaHash = pre.photoHash();

}

void MainWindow::on_pushButtonLogin_clicked() {
    m_client->connectToServer(ui->lineEditUsername->text().toAscii(), ui->lineEditPassword->text().toAscii());
    //qDebug() << m_client->configuration().getNetworkProxy().hostName();
    ui->stackedWidget->setCurrentIndex(1);
}

void MainWindow::on_pushButtonLogout_clicked() {
    if (m_client->isConnected()) {
        m_client->disconnectFromServer();
    }
    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::sendMessage(QString msg) {
    ContactPage* page = qobject_cast<ContactPage*>(sender());
    if (page) {
        QString bareJid = page->getBareJid();
        m_client->sendMessage(bareJid,msg);
    }
}
